use crate::business::app_state::AppState;
use crate::business::websocket::dto::common_dto::{ExceptionResp, OkListResp, OkResp};
use crate::business::websocket::dto::im_message_dto::{MessageObject, MessageObjectsReq, MessageReadReq, MessageWithdrawReq};
use crate::business::websocket::send_data_handle::send_data_async;
use crate::business::websocket::send_data_router::{RpcRequest, RpcResponse};

pub struct RpcMessageService;

impl RpcMessageService {
    pub async fn send_message(app_state: AppState, message_object: MessageObject) -> Result<OkResp, ExceptionResp> {
        let response = send_data_async(app_state.clone(), RpcRequest::SendMessage(message_object)).await;
        if let RpcResponse::SendMessageResponse(result) = response {
            return result;
        }

        Err(ExceptionResp::new("缺少对应的处理器".to_string()))
    }

    pub async fn send_messages(app_state: AppState, message_objects_req: MessageObjectsReq) -> Result<OkListResp, ExceptionResp> {
        let response = send_data_async(app_state.clone(), RpcRequest::SendMessages(message_objects_req)).await;
        if let RpcResponse::SendMessagesResponse(result) = response {
            return result;
        }

        Err(ExceptionResp::new("缺少对应的处理器".to_string()))
    }

    pub async fn send_read_message(app_state: AppState, message_read_req: MessageReadReq) -> Result<OkResp, ExceptionResp> {
        if message_read_req.message_ids.len() < 1 {
            return Err(ExceptionResp::new("messageIds为空".to_string()))
        }
        let response = send_data_async(app_state.clone(), RpcRequest::ReadMessage(message_read_req)).await;
        if let RpcResponse::ReadMessageResponse(result) = response {
            return result;
        }

        Err(ExceptionResp::new("缺少对应的处理器".to_string()))
    }

    pub async fn send_withdraw_message(app_state: AppState, message_withdraw_req: MessageWithdrawReq) -> Result<OkResp, ExceptionResp> {
        if message_withdraw_req.message_ids.len() < 1 {
            return Err(ExceptionResp::new("messageIds为空".to_string()))
        }
        let response = send_data_async(app_state.clone(), RpcRequest::WithdrawMessage(message_withdraw_req)).await;
        if let RpcResponse::WithdrawMessageResponse(result) = response {
            return result;
        }

        Err(ExceptionResp::new("缺少对应的处理器".to_string()))
    }
}